package assignment.quocthai;

import android.content.ContentValues;
import android.content.Context;
import android.database.Cursor;
import android.database.sqlite.SQLiteDatabase;
import android.util.Log;

public class MyAccountDAO {		
	private MyDatabaseHelper dbHelper;
	private SQLiteDatabase db;
	
	public final static String ACCOUNT_TABLE = "account";
	public final static String SERVER_NAME_COL = "server_name";
	public final static String USERNAME_COL = "username";
	public final static String PASSWORD_COL = "password";
	public final static String ID_COL = "id";
	
	public MyAccountDAO(Context context){
		dbHelper = new MyDatabaseHelper(context);
		db = dbHelper.getWritableDatabase();
	}
	
	public long insertAccount(String servername, String username, String password){
		ContentValues values = new ContentValues();
		values.put(SERVER_NAME_COL, servername);
		values.put(USERNAME_COL, username);
		values.put(PASSWORD_COL, password);
		return db.insert(ACCOUNT_TABLE, null, values);
	}
	
	public int updateAccount(String id, String servername, String username, String password){
		ContentValues values = new ContentValues();
		values.put(SERVER_NAME_COL, servername);
		values.put(USERNAME_COL, username);
		values.put(PASSWORD_COL, password);
		return db.update(ACCOUNT_TABLE, values, ID_COL + "=?", new String[]{id});
	}
	
	public boolean deleteAccount(String id){
		return db.delete(ACCOUNT_TABLE, ID_COL + "=?", new String[]{id}) > 0;
	}
	
	public boolean deleteAccountByServerName(String servername){
		return db.delete(ACCOUNT_TABLE, SERVER_NAME_COL + "=?", new String[]{servername}) > 0;
	}
	
	public Cursor getAllAccount(){
		String[] cols = new String[]{ID_COL, SERVER_NAME_COL, USERNAME_COL, PASSWORD_COL};
		boolean distinct = true;
		Cursor c = db.query(distinct, ACCOUNT_TABLE, cols, null, null, null, null, null, null);
//		if(c != null){
//			c.moveToFirst();
//		}
		return c;
	}
	
	public String getLastAccountID(){
		Cursor c = db.query(ACCOUNT_TABLE, null, ID_COL , null, null, null, ID_COL + " desc", "1");
		c.moveToFirst();
		Log.i("last id account", c.getString(c.getColumnIndex("id")));
		String lastID = c.getString(c.getColumnIndex("id"));
		c.close();
		return lastID;
	}
}
